package cn.imvc.app.models;

import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Brand;
import cn.imvc.app.repositories.BrandRepository;
import cn.imvc.data.domain.ViewRequest;
/**
 * 
 * @author zhy
 * @date 2016年7月22日下午2:22:55
 *
 */
@Service
public class BrandModelImpl implements BrandModel{

	@Autowired
	BrandRepository brandRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<Brand> find(ViewRequest viewRequest) {
		
		return brandRepository.findAll(viewRequest);
	}

	public Brand get(int id) {
		
		return brandRepository.getOne(id);
	}

	public int save(Brand brand) {
		String code = brand.getCode();
		String name = brand.getName();
		List<Brand> bc = brandRepository.findByCode(code);
		List<Brand> bn = brandRepository.findByName(name);
		if(bc.size()>0){
			return 0;
		}else if(bn.size()>0){
			return -1;
		}
		brandRepository.saveAndFlush(brand);
		return 1;
	}

	public int update(int id,Brand brand) {
		Brand loadBrand = brandRepository.getOne(id);
		String code  = brand.getCode();
		String name = brand.getName();
		List<Brand> bc = brandRepository.findByCode(code);
		List<Brand> bn = brandRepository.findByName(name);
		if(bc.size()>0&&!code.equals(loadBrand.getCode())){
			return 0;
		}else if(bn.size()>0&&!name.equals(loadBrand.getName())){
			return -1;
		}
		BeanUtils.copyProperties(brand, loadBrand, new String[]{"id"});
		brandRepository.saveAndFlush(loadBrand);
		return 1;
	}

	public String delete(int id) {
	    String result = refRelationModel.deleteDateCheck("brand", "id", id);
	    if(result.equals("")){
	    	brandRepository.delete(id);
	    	return "";
	    }else{
	    	return result;
	    }
	}

	public void deleteBatch(int[] ids) {
	
		for(int id : ids) {
		brandRepository.delete(id);
	    }
		
	}

}
